﻿// owner 蒋家伟

#include "ObjectReflectDefine.h"

// jsdk
#include "UniqueId.h"
#include "ObjectReflectFactory.h"
#include "Dbg_Warn_Define.h"

using namespace jsdk;

jsdk::OwnerPtr<jsdk::DBSchemaObject> jsdk::ObjectReflectUtils::getObjectReflectImp(const UniqueId& uid, const char* pClassId)
{
    std::wstring classIdStr;
    if (pClassId)
    {
        classIdStr.swap(StringUtils::toWString(pClassId));
    }
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(uid.isValid(), L"获取反射对象时, " + classIdStr + L"使用了无效的UID", L"蒋家伟", L"2023-11-13");
    return ObjectReflectFactory::get().getReflectObject(uid);
}

bool jsdk::ObjectReflectUtils::schemaObjectUnserialize(const JsonObject& jsonObject, const std::wstring& className, IFieldReflectManager& fieldReflectManager)
{
    DBG_WARN_AND_RETURN_FALSE_UNLESS(jsonObject.IsObject(), className + L" 的反流的对象不是Object对象", L"蒋家伟", L"2023-12-19");
    for (auto iter = jsonObject.MemberBegin(); iter != jsonObject.MemberEnd(); ++iter)
    {
        const std::wstring& varName = jsdk::StringUtils::toWString(iter->name.GetString()); 
        jsdk::IClassFieldDescriptor* pClassFieldDescriptor = fieldReflectManager.getFieldDescriptor(varName); 
        DBG_WARN_AND_RETURN_FALSE_UNLESS(pClassFieldDescriptor, className + std::wstring(L"的成员变量: ") + varName + L"缺少字段描述符", L"蒋家伟", L"2023-11-29"); 
        bool success = pClassFieldDescriptor->unserialize(iter->value); 
        DBG_WARN_AND_RETURN_FALSE_UNLESS(success, className + std::wstring(L"的成员变量: ") + varName + L"反流失败", L"蒋家伟", L"2023-11-29"); 
    }
    return true;
}

bool jsdk::ObjectReflectUtils::registerReflectClassDescriptorImp(const UniqueId& uid, const std::wstring& classTypeName, const reflectFun& fun)
{
    DBG_WARN_AND_RETURN_FALSE_UNLESS(uid.isValid(), L"注册反射对象时, " + classTypeName + L"使用了无效的UID", L"蒋家伟", L"2023-11-13");
    bool success = ObjectReflectFactory::get().registerReflectClassDescriptor(uid, classTypeName, fun);
    DBG_WARN_AND_RETURN_FALSE_UNLESS(success, L"UID : " + uid.toString() + L" 重复注册, 类型名称 : " + classTypeName, L"蒋家伟", L"2023-11-13");
    return true;
}

jsdk::IFieldReflectManager* jsdk::ObjectReflectUtils::getFieldReflectManagerImp(const UniqueId& uid, void* pClassAddress)
{
    DBG_WARN_AND_RETURN_FALSE_UNLESS(uid.isValid(), L"获取字段反射管理器时使用了无效的UID", L"蒋家伟", L"2023-11-13");
    return ObjectReflectFactory::get().getFieldReflectManager(uid, pClassAddress);
}
